package com.reggie.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.reggie.acl.dataobject.User;
import com.reggie.acl.mapper.UserMapper;
import com.reggie.common.enums.ResponseCode;
import com.reggie.common.exception.ReggieException;
import com.reggie.common.util.AssertUtils;
import com.reggie.service.model.request.UserLoginRequest;
import com.reggie.service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author yth
 * @since 2023-02-04
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public User login(UserLoginRequest request) {
        AssertUtils.nonNull(request, ResponseCode.CLIENT_ERROR);
        AssertUtils.nonNull(request.getPhone(), ResponseCode.CLIENT_ERROR);
        AssertUtils.nonNull(request.getCode(), ResponseCode.CLIENT_ERROR);

        Object storeCode = redisTemplate.opsForValue().get(request.getPhone());

        if (storeCode == null || !storeCode.equals(request.getCode())) {
            // 验证码匹配失败
            throw new ReggieException(ResponseCode.CLIENT_ERROR, "验证码不匹配");
        }

        LambdaQueryWrapper<User> wrapper = Wrappers
                .lambdaQuery(User.class)
                .eq(User::getPhone, request.getPhone());
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            // 注册用户
            user = new User();
            user.setPhone(request.getPhone());
            user.setStatus(1);
            userMapper.insert(user);
        }
        redisTemplate.delete(request.getPhone());
        return user;
    }

    @Override
    public Optional<User> getById(long userId) {
        return Optional.ofNullable(userMapper.selectById(userId));
    }


}
